import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../core/routes/app_routes.dart';
import '../widgets/bottom_navigation_widget.dart';

/// 主布局组件
/// Main layout component for the application
class MainLayout extends StatefulWidget {
  /// 当前页面内容
  /// Current page content
  final Widget child;
  
  /// 当前选中的导航索引
  /// Currently selected navigation index
  final int currentIndex;
  
  /// 是否显示底部导航栏
  /// Whether to show bottom navigation bar
  final bool showBottomNavigation;
  
  /// 是否显示浮动操作按钮
  /// Whether to show floating action button
  final bool showFloatingActionButton;
  
  /// 自定义浮动操作按钮
  /// Custom floating action button
  final Widget? customFloatingActionButton;
  
  /// 应用栏标题
  /// App bar title
  final String? appBarTitle;
  
  /// 是否显示应用栏
  /// Whether to show app bar
  final bool showAppBar;
  
  /// 应用栏操作按钮
  /// App bar actions
  final List<Widget>? appBarActions;
  
  /// 背景颜色
  /// Background color
  final Color? backgroundColor;

  const MainLayout({
    super.key,
    required this.child,
    this.currentIndex = 0,
    this.showBottomNavigation = true,
    this.showFloatingActionButton = false,
    this.customFloatingActionButton,
    this.appBarTitle,
    this.showAppBar = true,
    this.appBarActions,
    this.backgroundColor,
  });

  @override
  State<MainLayout> createState() => _MainLayoutState();
}

class _MainLayoutState extends State<MainLayout>
    with TickerProviderStateMixin {
  late AnimationController _fabAnimationController;
  late Animation<double> _fabScaleAnimation;
  late Animation<double> _fabRotationAnimation;
  
  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  @override
  void dispose() {
    _fabAnimationController.dispose();
    super.dispose();
  }

  /// 初始化动画
  /// Initialize animations
  void _initAnimations() {
    _fabAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    
    _fabScaleAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fabAnimationController,
      curve: Curves.elasticOut,
    ));
    
    _fabRotationAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fabAnimationController,
      curve: Curves.easeInOut,
    ));
    
    // 启动FAB动画
    // Start FAB animation
    if (widget.showFloatingActionButton) {
      _fabAnimationController.forward();
    }
  }

  @override
  void didUpdateWidget(MainLayout oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 处理FAB显示状态变化
    // Handle FAB visibility change
    if (oldWidget.showFloatingActionButton != widget.showFloatingActionButton) {
      if (widget.showFloatingActionButton) {
        _fabAnimationController.forward();
      } else {
        _fabAnimationController.reverse();
      }
    }
  }

  /// 处理底部导航点击
  /// Handle bottom navigation tap
  void _onBottomNavigationTap(int index) {
    // 根据索引导航到对应页面
    // Navigate to corresponding page based on index
    switch (index) {
      case 0:
        Get.offAllNamed(AppRoutes.home);
        break;
      case 1:
        Get.offAllNamed(AppRoutes.history);
        break;
      case 2:
        Get.offAllNamed(AppRoutes.analytics);
        break;
      case 3:
        Get.offAllNamed(AppRoutes.settings);
        break;
    }
  }

  /// 处理浮动操作按钮点击
  /// Handle floating action button tap
  void _onFloatingActionButtonTap() {
    // 导航到记录页面
    // Navigate to record page
    Get.toNamed(AppRoutes.record);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: widget.backgroundColor ?? AppColors.background,
      
      // 应用栏
      // App bar
      appBar: widget.showAppBar ? _buildAppBar() : null,
      
      // 主体内容
      // Body content
      body: SafeArea(
        child: widget.child,
      ),
      
      // 浮动操作按钮
      // Floating action button
      floatingActionButton: widget.showFloatingActionButton
          ? _buildFloatingActionButton()
          : null,
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      
      // 底部导航栏
      // Bottom navigation bar
      bottomNavigationBar: widget.showBottomNavigation
          ? _buildBottomNavigationBar()
          : null,
      
      // 抽屉
      // Drawer
      drawer: _buildDrawer(),
    );
  }

  /// 构建应用栏
  /// Build app bar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: widget.appBarTitle != null
          ? Text(
              widget.appBarTitle!,
              style: AppTextStyles.headlineSmall.copyWith(
                color: AppColors.textPrimary,
                fontWeight: FontWeight.w600,
              ),
            )
          : null,
      backgroundColor: AppColors.surfaceLight,
      elevation: 0,
      centerTitle: true,
      leading: _buildAppBarLeading(),
      actions: widget.appBarActions,
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(1),
        child: Container(
          height: 1,
          color: AppColors.borderColor,
        ),
      ),
    );
  }

  /// 构建应用栏前导按钮
  /// Build app bar leading button
  Widget? _buildAppBarLeading() {
    // 如果是主页面，不显示任何按钮（左滑菜单已可用）
    // If it's main page, don't show any button (left swipe menu is available)
    if (widget.currentIndex >= 0 && widget.currentIndex <= 3) {
      return null;
    }
    
    // 其他页面显示返回按钮
    // Other pages show back button
    return IconButton(
      icon: const Icon(
        Icons.arrow_back_ios,
        color: AppColors.textPrimary,
      ),
      onPressed: () {
        Get.back();
      },
    );
  }

  /// 构建浮动操作按钮
  /// Build floating action button
  Widget _buildFloatingActionButton() {
    if (widget.customFloatingActionButton != null) {
      return widget.customFloatingActionButton!;
    }
    
    return AnimatedBuilder(
      animation: _fabAnimationController,
      builder: (context, child) {
        return Transform.scale(
          scale: _fabScaleAnimation.value,
          child: Transform.rotate(
            angle: _fabRotationAnimation.value * 0.1,
            child: Container(
              width: 64,
              height: 64,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    AppColors.primary,
                    AppColors.primary.withOpacity(0.8),
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(32),
                boxShadow: [
                  BoxShadow(
                    color: AppColors.primary.withOpacity(0.4),
                    blurRadius: 16,
                    offset: const Offset(0, 8),
                    spreadRadius: 2,
                  ),
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 8,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: _onFloatingActionButtonTap,
                  borderRadius: BorderRadius.circular(32),
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(32),
                    ),
                    child: const Icon(
                      Icons.add_rounded,
                      color: Colors.white,
                      size: 32,
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建底部导航栏
  /// Build bottom navigation bar
  Widget _buildBottomNavigationBar() {
    return BottomNavigationWidget(
      currentIndex: widget.currentIndex,
      onTap: _onBottomNavigationTap,
    );
  }

  /// 构建抽屉
  /// Build drawer
  Widget? _buildDrawer() {
    return Drawer(
      backgroundColor: AppColors.surfaceLight,
      child: SafeArea(
        child: Column(
          children: [
            // 抽屉头部
            // Drawer header
            _buildDrawerHeader(),
            
            // 抽屉菜单项
            // Drawer menu items
            Expanded(
              child: _buildDrawerItems(),
            ),
            
            // 抽屉底部
            // Drawer footer
            _buildDrawerFooter(),
          ],
        ),
      ),
    );
  }

  /// 构建抽屉头部
  /// Build drawer header
  Widget _buildDrawerHeader() {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingLarge),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: AppColors.primaryGradient,
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 应用图标
          // App icon
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(30),
            ),
            child: const Icon(
              Icons.psychology,
              color: Colors.white,
              size: 32,
            ),
          ),
          
          const SizedBox(height: AppConstants.paddingMedium),
          
          // 应用名称
          // App name
          Text(
            AppConstants.appName,
            style: AppTextStyles.headlineSmall.copyWith(
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
          
          const SizedBox(height: 4),
          
          // 应用描述
          // App description
          Text(
            '记录情绪，疗愈心灵',
            style: AppTextStyles.bodyMedium.copyWith(
              color: Colors.white.withOpacity(0.8),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建抽屉菜单项
  /// Build drawer menu items
  Widget _buildDrawerItems() {
    final menuItems = [
      _DrawerItem(
        icon: Icons.home_outlined,
        activeIcon: Icons.home,
        title: '首页',
        route: AppRoutes.home,
        isSelected: widget.currentIndex == 0,
      ),
      _DrawerItem(
        icon: Icons.history_outlined,
        activeIcon: Icons.history,
        title: '历史记录',
        route: AppRoutes.history,
        isSelected: widget.currentIndex == 1,
      ),
      _DrawerItem(
        icon: Icons.analytics_outlined,
        activeIcon: Icons.analytics,
        title: '趋势分析',
        route: AppRoutes.analytics,
        isSelected: widget.currentIndex == 2,
      ),
      _DrawerItem(
        icon: Icons.settings_outlined,
        activeIcon: Icons.settings,
        title: '设置',
        route: AppRoutes.settings,
        isSelected: widget.currentIndex == 3,
      ),
      const Divider(),
      _DrawerItem(
        icon: Icons.help_outline,
        activeIcon: Icons.help,
        title: '帮助与反馈',
        onTap: () {
          Get.back();
          _showHelpDialog();
        },
      ),
      _DrawerItem(
        icon: Icons.info_outline,
        activeIcon: Icons.info,
        title: '关于应用',
        onTap: () {
          Get.back();
          _showAboutDialog();
        },
      ),
    ];
    
    return ListView.builder(
      padding: const EdgeInsets.symmetric(
        vertical: AppConstants.paddingSmall,
      ),
      itemCount: menuItems.length,
      itemBuilder: (context, index) {
        final item = menuItems[index];
        
        if (item is Divider) {
          return const Divider(
            color: AppColors.borderColor,
            height: 1,
            indent: AppConstants.paddingMedium,
            endIndent: AppConstants.paddingMedium,
          );
        }
        
        return _buildDrawerItem(item as _DrawerItem);
      },
    );
  }

  /// 构建抽屉菜单项
  /// Build drawer menu item
  Widget _buildDrawerItem(_DrawerItem item) {
    return Container(
      margin: const EdgeInsets.symmetric(
        horizontal: AppConstants.paddingSmall,
        vertical: 2,
      ),
      decoration: BoxDecoration(
        color: item.isSelected
            ? AppColors.primary.withOpacity(0.1)
            : Colors.transparent,
        borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
      ),
      child: ListTile(
        leading: Icon(
          item.isSelected ? item.activeIcon : item.icon,
          color: item.isSelected
              ? AppColors.primary
              : AppColors.textSecondary,
        ),
        title: Text(
          item.title,
          style: AppTextStyles.bodyMedium.copyWith(
            color: item.isSelected
                ? AppColors.primary
                : AppColors.textPrimary,
            fontWeight: item.isSelected
                ? FontWeight.w600
                : FontWeight.normal,
          ),
        ),
        onTap: () {
          Get.back(); // 关闭抽屉
          
          if (item.onTap != null) {
            item.onTap!();
          } else if (item.route != null) {
            Get.offAllNamed(item.route!);
          }
        },
      ),
    );
  }

  /// 构建抽屉底部
  /// Build drawer footer
  Widget _buildDrawerFooter() {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      child: Column(
        children: [
          const Divider(color: AppColors.borderColor),
          
          const SizedBox(height: AppConstants.paddingSmall),
          
          // 版本信息
          // Version info
          Text(
            '版本 ${AppConstants.appVersion}',
            style: AppTextStyles.bodySmall.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  /// 显示帮助对话框
  /// Show help dialog
  void _showHelpDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('帮助与反馈'),
        content: const Text(
          '如果您在使用过程中遇到任何问题或有改进建议，\n'
          '请通过以下方式联系我们：\n\n'
          '• 邮箱：support@emotionrecord.com\n'
          '• 微信：EmotionRecord\n'
          '• QQ群：123456789',
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示关于对话框
  /// Show about dialog
  void _showAboutDialog() {
    Get.dialog(
      AlertDialog(
        title: Text(AppConstants.appName),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('版本：${AppConstants.appVersion}'),
            const SizedBox(height: 8),
            const Text(
              '情绪记录疗愈应用是一款帮助用户记录和管理情绪的工具，\n'
              '通过科学的方法帮助用户更好地了解自己的情绪状态，\n'
              '促进心理健康和个人成长。',
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}

/// 抽屉菜单项数据类
/// Drawer menu item data class
class _DrawerItem {
  final IconData icon;
  final IconData activeIcon;
  final String title;
  final String? route;
  final VoidCallback? onTap;
  final bool isSelected;

  const _DrawerItem({
    required this.icon,
    required this.activeIcon,
    required this.title,
    this.route,
    this.onTap,
    this.isSelected = false,
  });
}